package com.bp.hearthealth.pulse.lnapps.ads.timer

import android.os.Handler
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad.AdMobRewardedAdManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil


object AppTimer {
    private lateinit var timerObserver: TimerObservable
    private var startTime: Long = 0
    private var elapsedTime: Long = 0
    private var handler: Handler? = null
    fun start() {
//        startTime = System.currentTimeMillis() // 记录应用程序启动时间
//        startTimer()
//        observer()
    }

    private fun observer() {
        timerObserver = TimerObservable()
        timerObserver.registerObserver(AdMobNativeAdManager)
        timerObserver.registerObserver(AdMobRewardedAdManager)
        timerObserver.registerObserver(AdMobInterstitialAdManager)
        BpApplication.adMobOpenAdManager?.let {
            timerObserver.registerObserver(it)
        }
    }

    fun stop() {
//        unRegisterObserver()
//        stopTimer()
    }

    private fun unRegisterObserver() {
        timerObserver.unRegisterObserver(AdMobNativeAdManager)
        timerObserver.unRegisterObserver(AdMobRewardedAdManager)
        timerObserver.unRegisterObserver(AdMobInterstitialAdManager)
        BpApplication.adMobOpenAdManager?.let {
            timerObserver.unRegisterObserver(it)
        }
    }

    private fun startTimer() {
        handler = Handler()
        handler!!.post(timerRunnable)
    }

    private fun stopTimer() {
        handler!!.removeCallbacksAndMessages(null)
        handler!!.removeCallbacks(timerRunnable)
    }

    private val timerRunnable: Runnable = object : Runnable {
        override fun run() {
            elapsedTime = System.currentTimeMillis() - startTime
            if ((elapsedTime / 1000).toInt() > 60 * 60) {
                LogUtil.i("时间到，通过观察者模式释放缓存")
                //重置时间
                startTime = System.currentTimeMillis()
                timerObserver.notifyObserver()
            }
            handler!!.postDelayed(this, 1000)
        }
    }
}

